package controllers

import (
	"encoding/xml"
	"github.com/astaxie/beego"
)

type DemoController struct {
	beego.Controller
}

func (this *DemoController) Get() {
	//绑定数据渲染模板
	this.Data["Content"] = "模板渲染"
	str := this.GetString("n")
	beego.Info(str)
	//this.Ctx.WriteString("Get func")  //不能和模板渲染同时使用
	//strs := this.GetStrings("m")
	//beego.Info(strs)
	//i, err := this.GetInt("i")
	//if err!=nil{
	//	beego.Info(i)
	//}
	//b, err := this.GetBool("b")
	//if err!=nil{
	//	beego.Info(b)
	//}
	this.Layout = "layout.html"
	//小部分页面抽取
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["Title"] = "title.html"
	this.TplName ="models.html"
}

func (this *DemoController) Post() {
	str := this.GetString("str")
	//str := this.Input().Get("s")
	beego.Info(str)
	//strs := this.GetStrings("ss")  //多参数传入
	//beego.Info(strs)
	//this.Ctx.WriteString("Post func\n") //增
	//fmt.Printf("%v---%T", strs[0], strs[0])

	//返回json数据
	this.Data["json"] = str
	this.ServeJSON()
}

type XMLData struct {
	ServerName string `xml:"servername" json:"serverName"`
	Email string `xml:"email" json:"email"`
}

type ServerData struct {
	XMLName xml.Name `xml:"servers" json:"xmlName"`
	Version string `xml:"version,attr" json:"version"`
	Servers []XMLData `xml:"server" json:"servers"`
}

//<?xml version="1.0" encoding="utf-8"?>
//<servers version="1.0">
//<server>
//<servername>python</servername>
//<email>python@g.com</email>
//</server>
//<server>
//<servername>go</servername>
//<email>go@g.com</email>
//</server>
//</servers>

//获取xml数据
//需要在配置文件中配置copyrequestbody=true
func (this *DemoController) Xml() {
	var data ServerData
	//strs := string(this.Ctx.Input.RequestBody)
	//beego.Info(strs)
	//this.Ctx.WriteString(strs)
	//err := xml.Unmarshal(this.Ctx.Input.RequestBody, &data)
	err := xml.Unmarshal(this.Ctx.Input.RequestBody, &data)
	if err!=nil{
		this.Data["json"] = err
		this.ServeJSON()
	}
	beego.Info(data)
	this.Data["json"]= data
	this.ServeJSON()

}
